package com.example.redis.service.impl;

import com.example.redis.service.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @author Administrator
 * @date 2021/2/21 18:24
 * @desc
 */
@Slf4j
@Service
public class AsyncServiceImpl implements AsyncService {

    @Autowired
    private RedisLockRegistry redisLockRegistry;

    /**
     * 无法使用异步注解
     * ERROR The UNLINK command has failed (not supported on the Redis server?); falling back to the regular DELETE command
     */
//    @Async
    @Override
    public void doLock() {
        String lockKey = "MY_LOCK";
        Lock lock = redisLockRegistry.obtain(lockKey);
        boolean result = false;
        try {
            //自定义lock等待时间3s
            result = lock.tryLock(3, TimeUnit.SECONDS);
            //只有拿到锁才往下执行
            if(!result){
                log.error("获取锁失败");
                return;
            }
            log.info("成功获取锁");
        } catch (Exception e) {
            log.error("加锁异常", e);
        } finally {
            if(result){
                try{
                    lock.unlock();
                }catch (Exception e){
                    log.error("-----------------解锁异常--------------------", e);
                }
            }
        }
    }
}
